<template>
  <div class="page">
    <nav-bar title="重点单位巡查" border></nav-bar>
    <div class="page-main" style="margin-top: 44px">
      <van-sticky class="page-scroll" :offset-top="44">
        <van-form
          validate-trigger="onSubmit"
          :show-error="false"
          ref="from"
          input-align="right"
          error-message-align="right"
          :label-width="120"
          @failed="onFailed"
          @submit="onSubmit"
        >
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.companyName"
            label="单位名称"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <van-field
            readonly
            label-class="van-cell__title_gray"
            v-model="inspectionDetail.companyTypeName"
            label="单位类型"
            right-icon="arrow"
            class="van-field__right-icon-white"
          />
          <!-- 第一次巡查 || 隐患已解决 -->
          <template
            v-if="
              inspectionDetail.inspectionRecord &&
              (!inspectionDetail.inspectionRecord.length ||
                inspectionDetail.inspectionRecord[inspectionDetail.inspectionRecord.length - 1].latentDangerResult ===
                  '1' ||
                inspectionDetail.inspectionRecord[inspectionDetail.inspectionRecord.length - 1].inspectionResult ===
                  '0')
            "
          >
            <van-field
              required
              readonly
              clickable
              name="inspectionResultCompanyName"
              v-model="formParams.inspectionResultCompanyName"
              label="巡查结果"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.inspectionResultCompanyName"
              @click="dictOpenPopup('inspectionResultCompany')"
            />
            <template v-if="formParams.inspectionResultCompany === '1'">
              <van-field
                required
                readonly
                clickable
                name="latentDangerLevelName"
                v-model="formParams.latentDangerLevelName"
                label="隐患风险级别"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.latentDangerLevelName"
                @click="dictOpenPopup('latentDangerLevel')"
              />
              <van-field
                required
                readonly
                clickable
                name="plannedCompletionTime"
                v-model="formParams.plannedCompletionTime"
                label="计划完成整改时间"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.plannedCompletionTime"
                @click="dateOpenPopup('plannedCompletionTime')"
              />
              <van-field
                required
                name="correctionManager"
                v-model="formParams.correctionManager"
                label="整改负责人"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="20"
                :rules="rules.correctionManager"
              />
              <van-field
                required
                name="correctionManagerPhone"
                v-model="formParams.correctionManagerPhone"
                label="负责人联系方式"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.correctionManagerPhone"
              />
              <van-field required label="隐患排查存在问题及说明" :label-width="180" readonly :border="false" />
              <van-field
                name="latentDangerDetail"
                v-model="formParams.latentDangerDetail"
                placeholder="请输入存在的隐患问题"
                rows="5"
                autosize
                type="textarea"
                show-word-limit
                :border="false"
                input-align="left"
                class="van-field__value--textarea"
                maxlength="200"
                :rules="rules.latentDangerDetail"
              />
              <van-field label="整治方案及措施" readonly :border="false" />
              <van-field
                name="latentDangerProgramme"
                v-model="formParams.latentDangerProgramme"
                placeholder="请输入整治方案及措施"
                rows="5"
                autosize
                type="textarea"
                show-word-limit
                :border="false"
                input-align="left"
                class="van-field__value--textarea"
                maxlength="500"
              />
            </template>
          </template>
          <!-- 再次巡查有隐患 -->
          <template v-else-if="inspectionDetail.inspectionRecord && inspectionDetail.inspectionRecord.length">
            <van-field
              required
              readonly
              clickable
              name="latentDangerResultName"
              v-model="formParams.latentDangerResultName"
              label="隐患解决情况"
              placeholder="请选择"
              right-icon="arrow"
              :rules="rules.latentDangerResultName"
              @click="dictOpenPopup('latentDangerResult')"
            />
            <template v-if="formParams.latentDangerResult === '1'">
              <van-field
                required
                readonly
                clickable
                name="actualFinishTime"
                v-model="formParams.actualFinishTime"
                label="实际完成整改时间"
                placeholder="请选择"
                right-icon="arrow"
                :rules="rules.actualFinishTime"
                @click="dateOpenPopup('actualFinishTime')"
              />
              <van-field
                required
                name="acceptanceCheckManager"
                v-model="formParams.acceptanceCheckManager"
                label="验收人"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :maxlength="20"
                :rules="rules.acceptanceCheckManager"
              />
              <van-field
                required
                name="acceptanceCheckManagerPhone"
                v-model="formParams.acceptanceCheckManagerPhone"
                label="验收人联系方式"
                placeholder="请输入"
                right-icon="arrow"
                class="van-field__right-icon-white"
                :rules="rules.acceptanceCheckManagerPhone"
              />
              <van-field label="事故隐患报告" readonly :border="false" />
              <van-field class="van-field__value--upload" :border="false" input-align="left">
                <template #input>
                  <van-uploader
                    name="latentDangerReportFileList"
                    accept=".docx,application/msword,application/pdf"
                    v-model="latentDangerReportFileList"
                    :preview-image="false"
                    :max-size="reportMaxSize"
                    :before-read="uploadBeforeRead"
                    :after-read="uploadAfterRead"
                  >
                    <div class="van-uploader__input--white">
                      <template v-if="latentDangerReportFileList.length">
                        <div class="van-uploader__input--content active">
                          <div class="upload-image">
                            <van-icon name="description" size="24" />
                          </div>
                          <div class="upload-text">
                            {{
                              latentDangerReportFileList[latentDangerReportFileList.length - 1].file.name.split('.')[1]
                            }}
                          </div>
                        </div>
                      </template>
                      <template v-else>
                        <div class="van-uploader__input--content">
                          <div class="upload-image">
                            <van-icon name="description" size="24" />
                          </div>
                          <div class="upload-text">点击上传</div>
                        </div>
                      </template>
                    </div>
                  </van-uploader>
                </template>
              </van-field>
              <van-field label="事故隐患治理方案" readonly :border="false" />
              <van-field class="van-field__value--upload" :border="false" input-align="left">
                <template #input>
                  <van-uploader
                    name="latentDangerProgrammeReportFileList"
                    accept=".docx,application/msword,application/pdf"
                    v-model="latentDangerProgrammeReportFileList"
                    :preview-image="false"
                    :max-size="reportMaxSize"
                    :before-read="uploadBeforeRead"
                    :after-read="uploadAfterRead"
                  >
                    <div class="van-uploader__input--white">
                      <template v-if="latentDangerProgrammeReportFileList.length">
                        <div class="van-uploader__input--content active">
                          <div class="upload-image">
                            <van-icon name="description" size="24" />
                          </div>
                          <div class="upload-text">
                            {{
                              latentDangerProgrammeReportFileList[
                                latentDangerProgrammeReportFileList.length - 1
                              ].file.name.split('.')[1]
                            }}
                          </div>
                        </div>
                      </template>
                      <template v-else>
                        <div class="van-uploader__input--content">
                          <div class="upload-image">
                            <van-icon name="description" size="24" />
                          </div>
                          <div class="upload-text">点击上传</div>
                        </div>
                      </template>
                    </div>
                  </van-uploader>
                </template>
              </van-field>
            </template>
          </template>
          <van-field label="现场照片/视频" readonly :border="false">
            <template #input>
              <van-radio-group v-model="imgAccept" direction="horizontal">
                <van-radio name="image/*">照片</van-radio>
                <van-radio name="video/*">视频</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field class="van-field__value--upload" input-align="left" :border="false">
            <template #input>
              <van-uploader
                name="imgFileList"
                v-model="imgFileList"
                max-count="9"
                capture="camera"
                :accept="imgAccept"
                :max-size="imgMaxSize"
                :preview-image="previewImage"
                :before-read="uploadBeforeRead"
                :after-read="uploadAfterRead"
                @click-preview="previewClick"
              >
                <template #preview-cover="file">
                  <template v-if="imgFormat.includes(file.file.name.split('.')[file.file.name.split('.').length - 1])">
                    <div class="van-uploader__preview-masker"></div>
                    <video-player
                      class="video-player vjs-custom-skin"
                      :playsinline="true"
                      :options="{
                        aspectRatio: '16:16',
                        sources: [
                          {
                            src: $config.ImageURl + file.file.url
                          }
                        ]
                      }"
                    ></video-player>
                  </template>
                </template>
                <div class="van-uploader__input--white">
                  <div class="van-uploader__input--content">
                    <div class="upload-image">
                      <img src="@/assets/images/basic/icon_camera@2x.png" />
                    </div>
                    <div class="upload-text">点击拍摄</div>
                  </div>
                </div>
              </van-uploader>
            </template>
          </van-field>
          <div style="padding: 0 16px" align="right">
            <van-button type="info" size="mini" native-type="button" @click="onEventReport">事件上报</van-button>
          </div>
          <div style="margin: 60px 16px">
            <van-row :gutter="23">
              <van-col span="12">
                <van-button block native-type="button" @click="onClear">清空</van-button>
              </van-col>
              <van-col span="12">
                <van-button block type="info" native-type="submit" :disabled="buttonDisabled">提交</van-button>
              </van-col>
            </van-row>
          </div>
        </van-form>
      </van-sticky>
    </div>
    <!-- 日期 -->
    <van-popup v-model="datePopupShow" round position="bottom" @close="date = new Date()">
      <van-datetime-picker
        v-model="date"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        :formatter="formatter"
        @cancel="datePopupShow = false"
        @confirm="dateOnConfirm"
      />
    </van-popup>
    <!-- 字典项 -->
    <van-popup v-model="dictPopupShow" round position="bottom" @close="dictValue = ''">
      <van-picker
        show-toolbar
        :default-index="dictData[dictType] && dictData[dictType].findIndex(o => o.code === dictValue)"
        :columns="dictData[dictType]"
        value-key="description"
        @cancel="dictPopupShow = false"
        @confirm="dictOnConfirm"
        @change="dictOnChange"
      />
    </van-popup>
    <!-- 视频预览 -->
    <gb-video :url="videoUrl" :show.sync="videoPopupShow"></gb-video>
  </div>
</template>
<script>
import InspectVisit from '@/api/inspectVisit'
import Upload from '@/mixins/upload'
import SelectPopup from '@/mixins/selectPopup'
import mapPlugin from '@/libs/mapPlugin'
import { residentNameReg, phoneReg } from '@/libs/regexp'
class FormParams {
  constructor() {
    // 网格编码
    this.gridCode = ''
    // 单位编码
    this.companyCode = ''
    // 巡查结果
    this.inspectionResult = ''
    this.inspectionResultCompany = ''
    this.inspectionResultCompanyName = ''

    // 存在隐患
    // 风险级别
    this.latentDangerLevel = ''
    this.latentDangerLevelName = ''
    // 隐患排查存在问题及说明
    this.latentDangerDetail = ''
    // 政治方案及措施
    this.latentDangerProgramme = ''
    // 计划完成时间
    this.plannedCompletionTime = ''
    // 整改负责人
    this.correctionManager = ''
    // 整改负责人电话
    this.correctionManagerPhone = ''

    // 隐患解决情况
    this.latentDangerResult = ''
    this.latentDangerResultName = ''
    // 隐患治理报告
    this.latentDangerReport = ''
    // 事故隐患治理方案
    this.latentDangerProgrammeReport = ''
    // 实际完成时间
    this.actualFinishTime = ''
    // 整改验收负责人
    this.acceptanceCheckManager = ''
    // 整改验收负责人电话
    this.acceptanceCheckManagerPhone = ''

    // 图片
    this.imageUrl = ''
  }
}
export default {
  mixins: [Upload, SelectPopup],
  data() {
    return {
      folder: 'inspection/company',
      // 现场照片视频
      imgAccept: 'image/*',
      imgMaxSize: 50 * 1024 * 1024,
      imgFileList: [],
      imgFormat: ['mp4', 'avi', 'mov'],
      videoPopupShow: false,
      videoUrl: '',
      // 事故隐患报告
      reportMaxSize: 1024 * 1024,
      latentDangerReportFileList: [],
      // 事故隐患治理方案
      latentDangerProgrammeReportFileList: [],

      dictTypes: 'inspectionResultCompany,latentDangerResult,latentDangerLevel,latentDangerType',

      inspectionDetail: {},
      formParams: new FormParams(),
      rules: {
        inspectionResultCompanyName: [{ required: true, message: '请选择巡查结果' }],
        latentDangerLevelName: [{ required: true, message: '请选择隐患风险级别' }],
        latentDangerDetail: [{ required: true, message: '请输入隐患排查存在问题及说明' }],
        plannedCompletionTime: [{ required: true, message: '请选择计划完成整改时间' }],
        correctionManager: [
          { required: true, message: '请输入整改负责人' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        correctionManagerPhone: [
          { required: true, message: '请输入联系方式' },
          { pattern: phoneReg, message: '请输入正确的联系方式' }
        ],
        latentDangerResult: [{ required: true, message: '请选择隐患解决情况' }],
        actualFinishTime: [{ required: true, message: '请选择实际完成整改时间' }],
        acceptanceCheckManager: [
          { required: true, message: '请输入验收负责人' },
          { pattern: residentNameReg, message: '请输入中文、英文和"·"' }
        ],
        acceptanceCheckManagerPhone: [
          { required: true, message: '请输入联系方式' },
          { pattern: phoneReg, message: '请输入正确的联系方式' }
        ]
      },
      buttonDisabled: false,

      goEventReportFlag: false
    }
  },
  created() {
    // 字典项
    this.getDict(this.dictTypes)
    this.getDetail()
  },
  methods: {
    getDetail() {
      InspectVisit.Company.detail({
        inspectionPointCode: this.$route.query.inspectionPointCode
      }).then(res => {
        const { status, data } = res.data
        if (status === 0) {
          this.inspectionDetail = data
          const inspectionRecord = this.inspectionDetail.inspectionRecord
          const recordLen = inspectionRecord.length
          // 有隐患 && 未解决
          if (
            recordLen &&
            inspectionRecord[recordLen - 1].inspectionResult === '1' &&
            inspectionRecord[recordLen - 1].latentDangerResult !== '1'
          ) {
            this.formParams = {
              ...inspectionRecord[recordLen - 1]
            }
            this.formParams.inspectionResultCompany = this.formParams.inspectionResult
            this.formParams.latentDangerResult = ''
            this.formParams.latentDangerResultName = ''
          }
        }
      })
    },
    dictOnChange() {
      if (this.dictType === 'inspectionResultCompany') {
        this.formParams.latentDangerLevel = ''
        this.formParams.latentDangerLevelName = ''
        this.formParams.latentDangerDetail = ''
        this.formParams.latentDangerProgramme = ''
        this.formParams.plannedCompletionTime = ''
        this.formParams.correctionManager = ''
        this.formParams.correctionManagerPhone = ''
      }
    },
    // 视频预览
    previewClick({ file }, detail) {
      const urlArr = this.imgFileList[detail.index].url.split('.')
      const suffix = urlArr[urlArr.length - 1]
      if (this.imgFormat.includes(suffix)) {
        this.videoPopupShow = true
        this.videoUrl = this.$config.ImageURl + this.imgFileList[detail.index].url
      }
    },
    // 表单 - 校验
    onFailed(errorInfo) {
      this.$refs.from.scrollToField(errorInfo.errors[0].name)
    },
    // 表单 - 提交
    onSubmit() {
      this.formParams.gridCode = this.$route.query.gridCode
      this.formParams.companyCode = this.inspectionDetail.companyCode
      // 图片
      this.formParams.imageUrl = this.imgFileList.map(o => o.url).join(',')
      // 事故隐患报告
      this.formParams.latentDangerReport = this.latentDangerReportFileList.length
        ? this.latentDangerReportFileList[this.latentDangerReportFileList.length - 1].url
        : ''
      // 事故隐患治理方案
      this.formParams.latentDangerProgrammeReport = this.latentDangerProgrammeReportFileList.length
        ? this.latentDangerProgrammeReportFileList[this.latentDangerProgrammeReportFileList.length - 1].url
        : ''
      this.formParams.inspectionResult = this.formParams.inspectionResultCompany
      this.buttonDisabled = true
      InspectVisit.Company.save(this.formParams)
        .then(res => {
          const { status } = res.data
          if (status === 0) {
            this.$toast.success('提交成功')
            if (this.goEventReportFlag) {
              this.goEventReport()
            } else {
              this.$router.go(-1)
            }
          } else {
            this.$toast.fail(res.data.message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    onClear() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否清空所有内容',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.formParams = new FormParams()
        })
    },
    // 事件上报
    onEventReport() {
      this.$dialog
        .confirm({
          title: '提示',
          message: '是否提交巡查结果',
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          this.goEventReportFlag = true
          this.$refs.from.submit()
        })
        .catch(() => {
          this.goEventReport()
        })
    },
    // 事件上报 - 跳转
    goEventReport() {
      mapPlugin.geocoder([this.inspectionDetail.longitude, this.inspectionDetail.latitude], result => {
        this.$router.push({
          name: 'event-report',
          params: {
            eventLocation: result.regeocode.formattedAddress,
            eventDescription: this.formParams.latentDangerDetail,
            fileList: this.imgFileList
          }
        })
      })
    }
  }
}
</script>
